<template>
  <el-popover placement="bottom-start" trigger="click" v-model="treeIsShow">
    <TreeDom ref="treeListDom" :choosed-data="choosedData" :get-list-fnc="getListFnc" :root-options="rootOptions" @chooseItem="chooseItem"></TreeDom>
    <InputDom slot="reference" @click="treeIsShow = true" :tree-is-show="treeIsShow" :root-options="rootOptions" :choosed-data="choosedData" @chooseItem="chooseItem" @clearAllItem="clearAllItem"></InputDom>
  </el-popover>
</template>
<script>
import { defineComponent, ref, watch, nextTick, onMounted, computed } from 'vue';
import InputDom from '@src/component/compomentV2/cascaderPower/components/inputDom/index.vue';
import TreeDom from '@src/component/compomentV2/cascaderPower/components/treeDom/index.vue';
export default defineComponent({
  name: 'CascaderPower',
  emits: ['update:modelValue'],
  props: {
    getListFnc: {
      type: Function,
      default: null,
    },
    rootOptions: {
      type: Object,
      default: () => ({}),
    },
    value: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    InputDom,
    TreeDom,
  },
  setup(props, { emit }) {
    const treeIsShow = ref(null);
    const treeListDom = ref(null);
    const choosedData = ref([]);
    onMounted(() => {
      initChooseItem(props.value);
      treeListDom.value.returnValueToDom();
    });
    watch(
      () => props.value,
      newValue => {
        initChooseItem(newValue);
        nextTick(() => {
          treeListDom.value.returnValueToDom();
        });
      },
      {
        deep: true,
      }
    );
    watch(
      () => choosedData.value,
      value => {
        emit('update:modelValue', value);
        emit('input', value);
      },
      {
        deep: true,
      }
    );

    function chooseItem(item) {
      const { key } = item;
      let index = choosedData.value.findIndex(item => item.key == key);
      if (index > -1) {
        choosedData.value.splice(index, 1);
      } else {
        choosedData.value.push(item);
      }
    }
    function clearAllItem() {
      choosedData.value = [];
    }
    function initChooseItem(arr) {
      choosedData.value = arr;
    }
    onMounted(() => {
      treeListDom.value.returnValueToDom();
    });

    return {
      treeIsShow,
      treeListDom,
      chooseItem,
      clearAllItem,
      initChooseItem,
      choosedData,
    };
  },
});
</script>
<style lang="scss" scoped></style>
